import sys
import os
from loguru import logger as _logger
from typing import Optional


def get_trace_id() -> str:
    """
    获取当前请求的追踪ID
    """
    try:
        from src.common.middleware.request_id import get_request_id
        request_id = get_request_id()
        return request_id if request_id else "no-trace"
    except ImportError:
        return "no-trace"


def format_message_with_trace(message: str) -> str:
    """
    为日志消息添加追踪ID
    """
    trace_id = get_trace_id()
    return f"[TraceId: {trace_id}] {message}"


class TraceLogger:
    """
    带追踪ID的日志记录器
    """
    
    def __init__(self, logger):
        self._logger = logger
    
    def debug(self, message: str, *args, **kwargs):
        self._logger.debug(format_message_with_trace(message), *args, **kwargs)
    
    def info(self, message: str, *args, **kwargs):
        self._logger.info(format_message_with_trace(message), *args, **kwargs)
    
    def warning(self, message: str, *args, **kwargs):
        self._logger.warning(format_message_with_trace(message), *args, **kwargs)
    
    def error(self, message: str, *args, **kwargs):
        self._logger.error(format_message_with_trace(message), *args, **kwargs)
    
    def critical(self, message: str, *args, **kwargs):
        self._logger.critical(format_message_with_trace(message), *args, **kwargs)
    
    def exception(self, message: str, *args, **kwargs):
        self._logger.exception(format_message_with_trace(message), *args, **kwargs)


# 判断是否是 Linux 系统
is_linux = os.name == "posix" and sys.platform.startswith("linux")

# 确保日志目录存在
if not os.path.exists("logs"):
    os.makedirs("logs")

# 移除默认的日志输出
_logger.remove()

# 添加日志文件（每天轮替一次，最多保留30天）
_logger.add(
    "logs/server_{time:YYYY-MM-DD}.log",  # 日志文件路径
    rotation="00:00",  # 每天午夜轮替日志文件
    retention="30 days",  # 最多保留30天的日志
    encoding="utf-8",  # 设置编码
    format="{time:YYYY-MM-DD HH:mm:ss.SSS} {level:<8} {name}:{function}:{line} - {message}",  # 文件日志格式
    level="INFO"  # 文件日志输出级别
)

# 添加控制台输出，保留颜色
_logger.add(
    sink=sys.stdout,  # 控制台输出
    format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> <level>{level:<8}</level> <cyan>{message}</cyan>",  # 控制台日志格式，保留颜色
    level="INFO",  # 控制台最低日志输出级别
    colorize=not is_linux  # 强制启用颜色
)

# 创建带追踪ID的日志实例
log = TraceLogger(_logger)